package com.example.demo02.interceptor;

import cn.hutool.core.util.IdUtil;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.pattern.PathPattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.List;

import static java.lang.Integer.MAX_VALUE;

@Component
@Order(-MAX_VALUE)
public class TraceInterceptor implements HandlerInterceptor {
    private final static  List<String> pathPatterns=new ArrayList<>();
    private static final List<String> excludePathPatterns=new ArrayList<>();
    static{
        pathPatterns.add("/**");
        excludePathPatterns.add("/error");

        // 放行swagger
        excludePathPatterns.add("/");
        excludePathPatterns.add("/csrf");
        excludePathPatterns.add("/swagger-resources/**");
        excludePathPatterns.add("/webjars/**");
        excludePathPatterns.add("/v2/**");
        excludePathPatterns.add("/swagger-ui.html/**");
    }
    public List<String> getPathPatterns(){
        return pathPatterns;
    }
    public List<String> getExcludePathPatterns(){
        return excludePathPatterns;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.put("trace_id", IdUtil.fastSimpleUUID());
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.remove("trace_id");
    }
}
